package test.config;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * Copyright © 2018 掌上医讯. All rights reserved.
 * 
 * @Title: WebSecurityConfig.java
 * @Prject: springwebsocket
 * @Package: test.config
 * @Description: TODO
 * @author: QuZening
 * @date: 2018年3月21日 上午11:24:15
 * @version: V1.0
 */
@SuppressWarnings("deprecation")
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/webjars/**").permitAll().antMatchers("/**").hasRole("USER").and()
				.formLogin().loginPage("/login").successHandler(new AuthenticationSuccessHandler() {

					@Override
					public void onAuthenticationSuccess(HttpServletRequest arg0, HttpServletResponse arg1,
							Authentication arg2) throws IOException, ServletException {
						Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
						if (principal != null && principal instanceof UserDetails) {
							UserDetails user = (UserDetails) principal;
							System.out.println("loginUser:" + user.getUsername());
							// 维护在session中
							arg0.getSession().setAttribute("userDetail", user);
							arg1.sendRedirect("/index");
						}
					}
				}).permitAll().and().csrf().disable();
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance()).withUser("admin")
				.password("admin").roles("USER").and().withUser("client").password("client").roles("USER");
	}
}
